package com.ljf.framework.context;

import com.ljf.framework.context.model.LjfRequest;
import com.ljf.framework.context.model.LjfResponse;
import com.ljf.framework.context.model.LjfStorage;
import com.ljf.framework.exception.LjfException;


/**
 * 上下文处理器 [ThreadLocal版本] ---- 对象存储器
 *
 *
 */
public class LjfContextForThreadLocalStorage {

	/**
	 * 基于 ThreadLocal 的 [Box存储器]
	 */
	public static ThreadLocal<Box> boxThreadLocal = new InheritableThreadLocal<Box>();

	/**
	 * 初始化 [Box存储器]
	 * @param request {@link LjfRequest}
	 * @param response {@link LjfResponse}
	 * @param storage {@link LjfStorage}
	 */
	public static void setBox(LjfRequest request, LjfResponse response, LjfStorage storage) {
		Box bok = new Box(request, response, storage);
		boxThreadLocal.set(bok);
	}

	/**
	 * 清除 [Box存储器]
	 */
	public static void clearBox() {
		boxThreadLocal.remove();
	}

	/**
	 * 获取 [Box存储器]
	 * @return see note
	 */
	public static Box getBox() {
		return boxThreadLocal.get();
	}

	/**
	 * 获取 [Box存储器], 如果为空则抛出异常
	 * @return see note
	 */
	public static Box getBoxNotNull() {
		Box box = boxThreadLocal.get();
		if(box ==  null) {
			throw new LjfException("未能获取有效的上下文");
		}
		return box;
	}

	/**
	 * 在 [Box存储器] 获取 [Request] 对象
	 *
	 * @return see note
	 */
	public static LjfRequest getRequest() {
		return getBoxNotNull().getRequest();
	}

	/**
	 * 在 [Box存储器] 获取 [Response] 对象
	 *
	 * @return see note
	 */
	public static LjfResponse getResponse() {
		return getBoxNotNull().getResponse();
	}

	/**
	 * 在 [Box存储器] 获取 [存储器] 对象
	 *
	 * @return see note
	 */
	public static LjfStorage getStorage() {
		return getBoxNotNull().getStorage();
	}


	/**
	 * 临时内部类，用于存储[request、response、storage]三个对象
	 * @author kong
	 */
	/**
	 * @author kong
	 *
	 */
	public static class Box {

		public LjfRequest request;

		public LjfResponse response;

		public LjfStorage storage;

		public Box(LjfRequest request, LjfResponse response, LjfStorage storage){
			this.request = request;
			this.response = response;
			this.storage = storage;
		}

		public LjfRequest getRequest() {
			return request;
		}

		public void setRequest(LjfRequest request) {
			this.request = request;
		}

		public LjfResponse getResponse() {
			return response;
		}

		public void setResponse(LjfResponse response) {
			this.response = response;
		}

		public LjfStorage getStorage() {
			return storage;
		}

		public void setStorage(LjfStorage storage) {
			this.storage = storage;
		}

		@Override
		public String toString() {
			return "Box [request=" + request + ", response=" + response + ", storage=" + storage + "]";
		}

	}

}
